from DrissionPage import ChromiumPage  # type: ignore
import pandas as pd  # type: ignore
import re, os
import threading
import warnings
import win32com.client
# 忽略警告
warnings.simplefilter(action='ignore', category=FutureWarning)


class Auxiliary_monitoring():

    # Dataframe设置不显示小数点
    pd.set_option('display.precision', 0)

    def __init__(self):
        self.result_output = self.df_output = ''
        self.df_index = [
            "广州市", "深圳市", "东莞市", "佛山市", "中山市", "惠州市", "珠海市", "江门市", "汕头市",
            "湛江市", "揭阳市", "肇庆市", "韶关市", "清远市", "茂名市", "梅州市", "潮州市", "阳江市",
            "河源市", "云浮市", "汕尾市", "科学城", "松山湖", "白云北", "知识城"
        ]
        self.page = ChromiumPage()
        # 获取第一个标签页对象
        self.tab1 = self.page.get_tab()
        # 新建一个标签页并访问另一个网址
        tab2 = self.page.new_tab()
        # 获取第二个标签页对象
        self.tab2 = self.page.get_tab(tab2)

    def Old_auxiliary(self, tab, df_index):
        '''旧的辅助监测'''
        global df_output
        tab.get('http://47.107.237.125:8012/#/login')
        shu = 0
        while not tab.ele('@id=userName'):
            shu += 1
            tab.refresh()
            tab.wait.ele_displayed('@id=userName')
            print(f'第{shu}次')
        userName = tab.ele('@id=userName')
        userName.input('zhoukejian')
        password = tab.ele('@id=password')
        password.input('123456\n')
        tab.wait.load_start()
        tab.get('http://47.107.237.125:8012/#/alarm-management/alarm-list')
        tab.wait(1)
        region = [
            "广州市", "东莞市", "江门市", "珠海市", "中山市", "阳江市", "河源市", "潮州市", "汕头市",
            "深圳市", "湛江市", "佛山市", "肇庆市", "云浮市", "揭阳市", "汕尾市", "惠州市"
        ]
        Old_assistance = []
        Input = tab.eles('t:input@@class=ant-select-search__field')
        for i in region:
            Input[2].input(i + "\n")
            tab.ele('查 询').click()
            tab.wait(0.5)
            Offline_quantity = Number_of_alarms = 0
            try:
                tab('t:li@@title=1').click()
                tab.wait(0.5)
                while True:
                    tr_list = tab('t:tbody@@class=ant-table-tbody').eles(
                        't:tr')
                    Number_of_alarms += len(tr_list)
                    Offline_quantity += len(tab.s_eles('FSU离线告警'))
                    下一页 = tab('t:li@@title=下一页')
                    if 'false' in 下一页.attr('aria-disabled'):
                        下一页.click()
                        tab.wait(0.5)
                    else:
                        break
            except:
                print(i, '无数据')
            Old_assistance.append([Offline_quantity, Number_of_alarms])
            # print(i, Offline_quantity, Number_of_alarms)
        Old_assistance = pd.DataFrame(Old_assistance,
                                      columns=['离线数量', '总告警数量'],
                                      index=region)

        df_output = Old_assistance.reindex(index=df_index)
        df_output.fillna(0, inplace=True)
        df_output = df_output.astype('int')
        df_output['告警数量'] = df_output['总告警数量'] - df_output['离线数量']
        df_output = df_output.clip(lower=0)
        # print(df_output)
        # self.df_output = df_output

    def neoadjuvant(self, tab, df_index):
        '''新的辅助监测'''
        global result_output
        tab.get('http://8.134.136.49:8090/#/login')
        tab('@placeholder=请输入用户名').input('admin')
        tab('@placeholder=请输入密码').input('zxm10!@#\n')
        tab('告警管理').click()
        tab('未选择区域').click()
        tab('广东省').click()
        tbody = tab('t:tbody').texts()
        df = pd.DataFrame([i.split('\n\t') for i in tbody])
        #只要中间的文字
        df[7] = df[7].str.slice(5, 8)
        # 删除包含特定字符的行
        df = df[~df[6].str.contains('空调')]
        df = df[~df[6].str.contains('测试')]
        df = df[~df[6].str.contains('gggx')]
        df = df[~df[6].str.contains('飞尚展台')]
        df = df[~df[6].str.contains('辅助')][[2, 7]]
        # print(df)

        Other_faults = df[~df[2].isin(['通信故障'])]
        Other_faults[2] = '其他故障'
        df = pd.concat([Other_faults, df[df[2].isin(['通信故障'])]],
                       ignore_index=True)
        result = df.groupby([7, 2]).size().unstack(fill_value=0)
        # print(result)
        result['总告警'] = result.apply(lambda x: x.sum(), axis=1)
        # print(result)
        result_output = result.reindex(index=df_index)
        result_output.fillna(0, inplace=True)
        # print(result_output)

    def run(self):
        thread1 = threading.Thread(target=Auxiliary_monitoring.Old_auxiliary,
                                   args=(self, self.tab1, self.df_index))
        thread2 = threading.Thread(target=Auxiliary_monitoring.neoadjuvant,
                                   args=(self, self.tab2, self.df_index))

        # 启动线程
        thread1.start()
        thread2.start()

        # 等待线程结束
        thread1.join()
        thread2.join()
        self.page.quit()

        ##数据修改(中山、深圳、清远、肇庆，云浮，潮州)  loc修改列
        for i in ['中山市', '深圳市', '清远市', '肇庆市', '云浮市', '潮州市']:
            result_output.loc[i] = 0

        #表格输出
        sum_out = pd.DataFrame(
            index=self.df_index,
            columns=['旧的离线', '旧的告警', '新的离线', '新的告警', '总离线数量', '总告警数量'])
        #旧的
        sum_out['旧的离线'] = df_output['离线数量']
        sum_out['旧的告警'] = df_output['告警数量']
        #新的
        sum_out['新的离线'] = result_output['通信故障']
        sum_out['新的告警'] = result_output['其他故障']
        #总数量
        # sum_out['总离线数量'] = df_output['离线数量'] + result_output['通信故障']
        # sum_out['总告警数量'] = df_output['告警数量'] + result_output['其他故障']
        sum_out['总离线数量'] = [
            f'=SUM(B{i+2},D{i+2})' for i in range(len(self.df_index))
        ]
        sum_out['总告警数量'] = [
            f'=SUM(C{i+2},E{i+2})' for i in range(len(self.df_index))
        ]

        try:
            # 获取 Excel 应用程序对象
            excel = win32com.client.GetActiveObject('Excel.Application')
            # 遍历所有打开的工作簿
            for workbook in excel.Workbooks:
                if workbook.Name == '辅助监控.xlsx':
                    # 关闭指定的工作簿
                    workbook.Close(
                        SaveChanges=False)  # 如果需要保存更改，改为 SaveChanges=True
                    print('成功关闭工作簿: 辅助监控.xlsx')
                    break
        except:
            pass
        try:
            sum_out.style.apply(lambda s: [
                'background-color: yellow;border: 1px solid;' if "旧的" in s.name
                else 'background-color: red;border: 1px solid;'
                if "新的" in s.name else None
            ] * len(s)).to_excel(
                os.path.join(os.path.expanduser("~"), 'Desktop') +
                '\\辅助监控.xlsx', )
        except:
            sum_out.to_excel(
                os.path.join(os.path.expanduser("~"), 'Desktop') +
                '\\辅助监控.xlsx', )
        #打开文件
        os.system(
            f"start {os.path.join(os.path.expanduser('~'), 'Desktop')}\辅助监控.xlsx"
        )

        ###旧版本
        # sum_out = pd.DataFrame(index=self.df_index, columns=['离线数量', '告警数量'])
        # sum_out['离线数量'] = df_output['离线数量'] + result_output['通信故障']
        # sum_out['告警数量'] = df_output['告警数量'] + result_output['其他故障']

        # with pd.ExcelWriter(
        #         os.path.join(os.path.expanduser("~"), 'Desktop') +
        #         '\\辅助监控.xlsx') as writer:
        #     sum_out.to_excel(writer, sheet_name='总表', index=True)
        #     df_output.to_excel(writer, sheet_name='旧的辅助', index=True)
        #     result_output.to_excel(writer, sheet_name='新的辅助', index=True)
        # os.system(
        #     f"start {os.path.join(os.path.expanduser('~'), 'Desktop')}\辅助监控.xlsx"
        # )
        print('辅助监控完成')


if __name__ == '__main__':
    # 实例化一个浏览器对象
    Monitoring = Auxiliary_monitoring()
    Monitoring.run()
